package com.example.bank.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author ：Leeziqiang
 * @description：TODO
 * @date ：2021/12/26 21:17
 */
public class OpenIdUtil {


    private static final String APPID = "wx7575406f03de4e16";
    private static final String SECRET = "b8303f0a394d2250946ce754b50b1af7";

    private static final String APPID2 = "wxe256aa4b09de434b";
    private static final String SECRET2 = "3ddbe1b13297f2963e058e072382d9d1";

    // appid和secret分别是小程序id和小程序密钥
    public static String getOpenId(String code) throws IOException {
        BufferedReader in = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+code+"&grant_type=authorization_code";
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String len;
            while ((len = in.readLine()) != null) {
                stringBuffer.append(len);
            }
            return stringBuffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}
